<?php
/**
 *  门店控制器
 * User: ws
 * Date: 2018/7/25
 * Time: 15:39
 */

namespace app\admin\controller;

class Store extends Init
{
    function _initialize()
    {
        parent::_initialize();
        $this->model = model('store');
    }
    function index(){
        if ($this->request->isAjax()) {
            $key = input('key')?input('key'):'';
            $map['name|phone|store_desc|address']  = array('like',"%$key%");

            $list = $this->model->get_list($map, '', input('limit'), 2);
            return json($result = ['code'=>0,'msg'=>'获取成功','data'=>$list['data'],'count'=>$list['total']]);
        }
        return view('list');
    }

    function add(){
        if(request()->isPost()){
            $params = $this->request->post();
            $params['store_desc'] = base64_decode($params['store_desc']);
            if(!empty($params['lag'])){
                $map = explode(",",$params['lag']);
                $params['lat'] = $map[0];
                $params['lng'] = $map[1];
            }
            $result = $this->model->add($params);
            if($result){
                return json(array('code'=>200,'msg'=>'添加成功'));
            }else{
                return json(array('code'=>0,'msg'=>'添加失败'));
            }
        }
        return view('add');
    }

    function edit(){
        if(request()->isPost()){
            $params = $this->request->post();
            $params['store_desc'] = base64_decode($params['store_desc']);
                if(empty($params['img'])){
                    unset($params['img']);
                }else{
                    $goodsI = $this->model->field('img')->where("store_id = {$params['store_id']}")->find();
                    $goodsIMG = $goodsI->toArray();
                    unlink('.'.$goodsIMG['img']);
                }

                if ($params['store_pass'] == '') {
                    unset($params['store_pass']);
                }

                if(empty($params['lag'])){
                    unset($params['lag']);
                }else{
                    $map = explode(",",$params['lag']);
                    $params['lat'] = $map[0];
                    $params['lng'] = $map[1];
                }
                $result = $this->model->edit($params);

            if($result){
                return json(array('code'=>200,'msg'=>'添加成功'));
            }else{
                return json(array('code'=>0,'msg'=>'添加失败'));
            }
        }

        if(input('id')){
            $list = $this->model->where('store_id',input('id'))->find()->toArray();
            return view('edit',['list'=>$list]);
        }
    }


    function del()
    {
        $where['store_id'] = input('store_id');
        $this->model->del($where);
        $result = $this->model->destroy(input('store_id'));
        if($result){
            return json(array('code'=>200,'msg'=>'删除成功'));
        }else{
            return json(array('code'=>0,'msg'=>'删除失败'));
        }
    }

}